package com.szewec.ps.ui.road.facilities.intersection.task;

import android.content.Context;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.viewpager.widget.PagerAdapter;

import com.alibaba.fastjson.JSON;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.databinding.ActivityVehicleLaneBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.response.ResponseData;
import com.szewec.ps.myinterface.BindEditTextViewValue;
import com.szewec.ps.myview.InputItem;
import com.szewec.ps.myview.indicator.IndicatorViewPager;
import com.szewec.ps.myview.indicator.OnTransitionTextListener;
import com.szewec.ps.myview.indicator.slidebar.DrawableBar;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.road.facilities.intersection.task.constants.Consts.LaneDirection;
import com.szewec.ps.ui.road.facilities.intersection.task.constants.Consts.Type;
import com.szewec.ps.ui.road.facilities.intersection.task.enums.RoadEnums;
import com.szewec.ps.ui.road.facilities.intersection.task.model.LaneDetail;
import com.szewec.ps.ui.road.facilities.intersection.task.model.VehicleLane;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.BeanUtils;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.ViewUtils;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.GsonUtil;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;

public class VehicleLaneActivity extends BaseActivity implements BindEditTextViewValue {
    private ActivityVehicleLaneBinding binding;

    private String flag;

    private IndicatorViewPager indicatorViewPager;
    private List<String> tabs = new ArrayList<>();
    private int lineNum = 4;
    private Point screenPoint;

    private DrawableBar drawableBar;
    private List<Integer> textWidths = new ArrayList<>();

    private VehicleLane vehicleLane = new VehicleLane();
    private VehicleLane newVehicleLane = new VehicleLane();

    private final List<Integer> laneNumList = new ArrayList<Integer>() {
        private static final long serialVersionUID = 6758530927834880381L;

        {
            add(1);
            add(2);
            add(3);
            add(4);
            add(5);
        }
    };
    private List<LaneDetail> laneDetails = new ArrayList<>();
    private List<String> guideArrowList = new ArrayList<>();

    private List<String> roadsideDividerList = new ArrayList<>();
    private List<String> dextroversionCanalizationList = new ArrayList<>();

    private int laneType = Type.IMPORT_LANE;

    private MyAdapter myAdapter;
    protected Map<Integer, View> myAdapterViews = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_vehicle_lane);
        ButterKnife.bind(this);

        Bundle presentValue = getIntent().getExtras();
        PresentValue<VehicleLane> value = (PresentValue<VehicleLane>) presentValue.getSerializable(Constants.EXTRA_KEY.VEHICLE_LANE);
        flag = value.getFlag();
        System.out.println("接收======================>" + flag);
        vehicleLane = value.getT();
        laneType = vehicleLane.getLaneType();
        lineNum = vehicleLane.getLaneNum() == null ? 1 : vehicleLane.getLaneNum();

        initTitleBar();
        initViewPage();
        initSelectData();
        initView();
        if (flag.equals(Constants.PRESENT_VALUE_FLAG.EDIT)) {
            setInputData();
        }
    }

    private void initTitleBar() {
        if (laneType == Type.IMPORT_LANE) {
            binding.titleBar.setTitle("进口道");
        } else {
            binding.titleBar.setTitle("出口道");
        }
        binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutClickListener(v -> {
            saveData();
            CommonUtils.showIsSave(VehicleLaneActivity.this, this::upTo);
        });
        binding.titleBar.setRightLayoutVisibility(View.VISIBLE);
        binding.titleBar.setRightTextVisibility(View.VISIBLE);
        binding.titleBar.setRightTextClickListener(v -> {
            saveData();
            if (BeanUtils.comparisonOutside(this.vehicleLane, newVehicleLane)) {
                BamToast.showText(this, Constants.ErrorMsg.NOT_UPDATE, false);
                return;
            }
            upTo();
        });
    }

    private void initViewPage() {
        float textSize = 14;
        binding.moretabIndicator.setOnTransitionListener(new OnTransitionTextListener().setColor(0xFF2A84FC, 0xFF333333).setSize(textSize, textSize));

        WindowManager winManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenPoint = new Point();
        winManager.getDefaultDisplay().getSize(screenPoint);
        drawableBar = new DrawableBar(VehicleLaneActivity.this, getDrawable(R.drawable.silde_block));

        binding.moretabViewPager.setOffscreenPageLimit(tabs.size() - 1);
        indicatorViewPager = new IndicatorViewPager(binding.moretabIndicator, binding.moretabViewPager);
        //监听页面改变
        indicatorViewPager.setOnIndicatorPageChangeListener((preItem, currentItem) -> {
            //每次改变页面把之前的数据存储下来
            drawableBar.setWidth(textWidths.get(currentItem));
            binding.moretabIndicator.setScrollBar(drawableBar);

            View view = myAdapterViews.get(preItem);
            if (view == null) {
                return;
            }
            LaneDetail detail = new LaneDetail();
            InputItem guideArrowIt = view.findViewById(R.id.it_guide_arrow);
            InputItem laneWidthIt = view.findViewById(R.id.it_line_width);
            if (laneWidthIt.getBigDecimalValue() != null) {
                //库存放。下标从1开始
                detail.setGuideArrow(guideArrowIt.getStringValue());
                detail.setLaneWidth(laneWidthIt.getBigDecimalValue());
                detail.setIndex(preItem);
                boolean t = false;
                for (int i = 0; i < laneDetails.size(); i++) {
                    if (laneDetails.get(i).getIndex().equals(preItem)) {
                        t = true;
                        laneDetails.set(preItem, detail);
                        break;
                    }
                }
                if (t) {
                    return;
                }
                laneDetails.add(detail);
            }
//            myAdapterViews.put(currentItem, myAdapter.getCurrentView());
//                System.out.println("add=====================>" + myAdapterViews.size());
        });
    }

    private void initSelectData() {
        guideArrowList = Arrays.asList(getResources().getStringArray(R.array.guide_arrow));
//        roadsideDividerList = Arrays.asList(getResources().getStringArray(R.array.roadside_divider));
        roadsideDividerList = RoadEnums.RoadsideDivider.getEnumValueList();
//        dextroversionCanalizationList = Arrays.asList(getResources().getStringArray(R.array.dextroversion_canalization));
        dextroversionCanalizationList = RoadEnums.DextroversionCanalization.getEnumValueList();
    }

    private void setInputData() {
        BeanUtils.stripTrailingZeros(vehicleLane);
        binding.itLineNum.setValue(vehicleLane.getLaneNum());
        binding.itSideRdNum.setValue(vehicleLane.getSideRdNum());
//        initViewPage(vehicleLane.getLaneNum());
//        LaneDetail t = JSON.parseObject("{\"guideArrow\":\"直行\",\"index\":0,\"laneWidth\":\"3.0\"}",LaneDetail.class);
        laneDetails = GsonUtil.GsonToList(vehicleLane.getLaneDetail(), LaneDetail.class);
//        laneDetails = JSON.parseArray(vehicleLane.getLaneDetail(), LaneDetail.class);
        initViewPageData(vehicleLane.getLaneNum());
        for (LaneDetail detail : laneDetails) {
            tabs.set(detail.getIndex(), detail.getGuideArrow());
        }
//        myAdapter = new MyAdapter();
        indicatorViewPager.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        indicatorViewPager.setCurrentItem(0, true);
//        myAdapterViews.put(0, myAdapter.getCurrentView());

        binding.itRoadsideDivider.setValue(RoadEnums.RoadsideDivider.getValueByKey(vehicleLane.getRoadsideDivider()));
        binding.itRoadsideDividerWidth.setValue(vehicleLane.getRoadsideDividerWidth());
        binding.itDextroversionCanalization.setValue(RoadEnums.DextroversionCanalization.getValueByKey(vehicleLane.getDextroversionCanalization()));
    }

    private void initViewPageData(int lineNum) {
        tabs.clear();
        textWidths.clear();
        if (laneType == Type.IMPORT_LANE) {
            //根据车道数加载不同个数的车道
            switch (lineNum) {
                case 1:
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT.getValue());
                    break;
                case 2:
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT_LEFT.getValue());
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT_RIGHT.getValue());
                    break;
                case 3:
                    tabs.add(RoadEnums.LaneDirection.LEFT_TURN.getValue());
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT.getValue());
                    tabs.add(RoadEnums.LaneDirection.RIGHT_TURN.getValue());
                    break;
                case 4:
                    tabs.add(RoadEnums.LaneDirection.LEFT_TURN.getValue());
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT.getValue());
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT.getValue());
                    tabs.add(RoadEnums.LaneDirection.RIGHT_TURN.getValue());
                    break;
                case 5:
                    tabs.add(RoadEnums.LaneDirection.LEFT_TURN.getValue());
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT_LEFT.getValue());
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT.getValue());
                    tabs.add(RoadEnums.LaneDirection.STRAIGHT_RIGHT.getValue());
                    tabs.add(RoadEnums.LaneDirection.RIGHT_TURN.getValue());
                    break;
            }
        } else {
            for (int i = 0; i < lineNum; i++) {
                tabs.add(RoadEnums.LaneDirection.STRAIGHT.getValue());
            }
        }
        indicatorViewPager.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        indicatorViewPager.setCurrentItem(0, true);
//        myAdapterViews.put(0, myAdapter.getCurrentView());
    }

    private void initView() {
        if (laneType == Type.EXIT_LANE) {
            binding.itLineNum.setItemName("出口车道数");
            binding.itDextroversionCanalization.setVisibility(View.GONE);
        }
        binding.itLineNum.setValue(1);
        tabs.add(RoadEnums.LaneDirection.STRAIGHT.getValue());
        myAdapter = new MyAdapter();
        indicatorViewPager.setAdapter(myAdapter);

//        myAdapterViews.put(0, myAdapter.getCurrentView());

        binding.itLineNum.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, laneNumList, binding.itLineNum.getSelectTextView(), (view, index) -> {
                binding.itLineNum.setValue(laneNumList.get(index));
                lineNum = laneNumList.get(index);
                initViewPageData(laneNumList.get(index));
            });
        });

        binding.itRoadsideDivider.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, roadsideDividerList, binding.itRoadsideDivider.getSelectTextView(), (view, index) ->
                    binding.itRoadsideDivider.setValue(roadsideDividerList.get(index)));
        });

        binding.itDextroversionCanalization.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, dextroversionCanalizationList, binding.itDextroversionCanalization.getSelectTextView(), (view, index) ->
                    binding.itDextroversionCanalization.setValue(dextroversionCanalizationList.get(index)));
        });
    }

    //保存数据到对象
    private void saveData() {
        BeanUtils.copyObj(this.vehicleLane, this.newVehicleLane);

        newVehicleLane.setLaneNum(binding.itLineNum.getIntValue());
        newVehicleLane.setSideRdNum(binding.itSideRdNum.getIntValue());

        View view = myAdapter.getCurrentView();
        int itemPosition = indicatorViewPager.getCurrentItem();

        LaneDetail detail = new LaneDetail();
        InputItem guideArrowIt = view.findViewById(R.id.it_guide_arrow);
        InputItem laneWidthIt = view.findViewById(R.id.it_line_width);
        //库存放。下标从1开始
        if (laneWidthIt.getBigDecimalValue() != null) {
            detail.setGuideArrow(guideArrowIt.getStringValue());
            detail.setLaneWidth(laneWidthIt.getBigDecimalValue());
            detail.setIndex(itemPosition);
            boolean t = true;
            for (int i = 0; i < laneDetails.size(); i++) {
                if (laneDetails.get(i).getIndex().equals(itemPosition)) {
                    t = false;
                    laneDetails.set(i, detail);
                    break;
                }
            }
            if (t) {
                laneDetails.add(detail);
            }
        }

        newVehicleLane.setLaneDetail(JSON.toJSONString(laneDetails));
//        vehicleLane.setLaneDetails(laneDetails);
        newVehicleLane.setRoadsideDivider(RoadEnums.RoadsideDivider.getKeyByValue(binding.itRoadsideDivider.getStringValue()));
        newVehicleLane.setRoadsideDividerWidth(binding.itRoadsideDividerWidth.getBigDecimalValue());
        newVehicleLane.setDextroversionCanalization(RoadEnums.DextroversionCanalization.getKeyByValue(binding.itDextroversionCanalization.getStringValue()));
        newVehicleLane.setLaneType(laneType);
        System.out.println(JSON.toJSONString(newVehicleLane));
    }

    /**
     * 导流走新增还是修改
     */
    private void upTo() {
        if (flag.equals(Constants.PRESENT_VALUE_FLAG.ADD)) {
            postData();
        } else if (flag.equals(Constants.PRESENT_VALUE_FLAG.EDIT)) {
            putData();
        }
    }

    /**
     * 存入后台
     */
    private void postData() {
        OkHttp.post("/tpms-plan-service/api/vehicle-lane/", newVehicleLane, result -> {
            ResponseData responseData = JSON.parseObject(result, ResponseData.class);
            if (responseData.getCode() == Constants.ResponseCode.SUCCESS) {
                BamToast.showText(this, responseData.getMsg(), true);
                setResult(Constants.RESULT_CODE.NEED_REFRESH);
                finish();
            } else {
                BamToast.showText(this, responseData.getMsg(), false);
            }
        });
    }

    //修改数据存入后台
    private void putData() {
        OkHttp.put("/tpms-plan-service/api/vehicle-lane/", newVehicleLane, result -> {
            ResponseData responseData = JSON.parseObject(result, ResponseData.class);
            if (responseData.getCode() == Constants.ResponseCode.SUCCESS) {
                BamToast.showText(this, responseData.getMsg(), true);
                setResult(Constants.RESULT_CODE.NEED_REFRESH);
                finish();
            } else {
                BamToast.showText(this, responseData.getMsg(), false);
            }
        });
    }

    //监听滑动
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return ViewUtils.dispatchTouchEvent(this, event);
    }

    @Override
    public void setObjValue() {

    }

    @Override
    public boolean checkLinkedDataAndFiles() {
        //判断是否修改了数据
        return !BeanUtils.comparisonOutside(this.vehicleLane, newVehicleLane);
    }


    /**
     * 适配器
     */
    public class MyAdapter extends IndicatorViewPager.IndicatorViewPagerAdapter {
        protected List<TextView> tabViews = new ArrayList<>();

        @Override
        public int getCount() {
            return tabs.size();
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.tab_top, container, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(tabs.get(position));
//            int padding = DisplayUtil.dipToPix(getApplicationContext(), 8);
            //因为wrap的布局 字体大小变化会导致textView大小变化产生抖动，这里通过设置textView宽度就避免抖动现象
            //1.3f是根据上面字体大小变化的倍数1.3f设置
            textView.setWidth(screenPoint.x / lineNum);
            textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            int textWidth = ViewUtils.getTextWidth(textView);
            textWidths.add(textWidth);
/*            if (position == 0) {
//            drawableBar.setWH(getTextWidth(textView), 3);
                drawableBar.setWidth(textWidth);
                binding.moretabIndicator.setScrollBar(drawableBar);
            }*/
            tabViews.add(textView);
            return textView;
        }

        @Override
        public View getViewForPage(int position, View convertView, ViewGroup container) {
//            View vi = myAdapterViews.get(position);
/*            if (vi != null) {
                indicatorViewPager.getViewPager().removeView(vi);
                return vi;
            }*/
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.page_lane_guide, container, false);
            }
            ImageView imageView = convertView.findViewById(R.id.iv_guide_arrow);
            InputItem guideArrowView = convertView.findViewById(R.id.it_guide_arrow);
            InputItem lineWidthView = convertView.findViewById(R.id.it_line_width);
            setImg(tabs.get(position), imageView);
            guideArrowView.setValue(tabs.get(position));
            guideArrowView.setSelectTypeClickListener(v -> {
                TextViewUtil.closeKeyboard(VehicleLaneActivity.this);
                RollUtil.alertBottomWheelOption(VehicleLaneActivity.this, guideArrowList, guideArrowView.getSelectTextView(), (view, index) -> {
                    guideArrowView.setValue(guideArrowList.get(index));
                    setImg(guideArrowList.get(index), imageView);
                    tabViews.get(position).setText(guideArrowList.get(index));
                    tabs.set(position, guideArrowList.get(index));
                });
            });
/*            if (position < laneDetails.size()) {
                lineWidthView.setValue(laneDetails.get(position).getLaneWidth());
            }*/
//            for (LaneDetail detail : laneDetails) {
//                if (detail.getIndex() == position) {
//                    guideArrowView.setValue(detail.getGuideArrow());
//                    lineWidthView.setValue(detail.getLaneWidth());
//                }
//            }
            System.out.println(position + "==========================>" + ((InputItem) convertView.findViewById(R.id.it_guide_arrow)).getStringValue());

            if (position == 4) {
                System.out.println(position + "==========================>" + ((InputItem) myAdapterViews.get(0).findViewById(R.id.it_guide_arrow)).getStringValue());
            }

            for (int i = 0; i < laneDetails.size(); i++) {
                if (laneDetails.get(i).getIndex() == position) {
                    guideArrowView.setValue(laneDetails.get(i).getGuideArrow());
                    lineWidthView.setValue(laneDetails.get(i).getLaneWidth());
                }
            }
//            if (myAdapterViews.get(position) == null) {
            myAdapterViews.put(position, convertView);
//            }
            return convertView;
        }

        @Override
        public int getItemPosition(Object object) {
            //这是ViewPager适配器的特点,有两个值 POSITION_NONE，POSITION_UNCHANGED，默认就是POSITION_UNCHANGED,
            // 表示数据没变化不用更新.notifyDataChange的时候重新调用getViewForPage
            return PagerAdapter.POSITION_UNCHANGED;
        }

        protected void setImg(String condition, ImageView imageView) {
            switch (condition) {
                case LaneDirection.LEFT_TURN:
                    imageView.setImageResource(R.mipmap.ic_left_turn);
                    break;
                case LaneDirection.STRAIGHT_LEFT:
                    imageView.setImageResource(R.mipmap.ic_straight_left);
                    break;
                case LaneDirection.STRAIGHT:
                    imageView.setImageResource(R.mipmap.ic_straight);
                    break;
                case LaneDirection.STRAIGHT_RIGHT:
                    imageView.setImageResource(R.mipmap.ic_straight_right);
                    break;
                case LaneDirection.RIGHT_TURN:
                    imageView.setImageResource(R.mipmap.ic_right_turn);
                    break;
            }
        }

        @Override
        public void notifyDataSetChanged() {
            this.tabViews.clear();
            super.notifyDataSetChanged();
        }
    }
}